package hospital.order.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.jdbc.StringUtils;
import hospital.common.helper.HttpRequestHelper;
import hospital.enums.OrderStatusEnum;
import hospital.exception.HospitalException;
import hospital.hospClient.HospFeignClient;
import hospital.model.order.OrderInfo;
import hospital.model.user.Patient;
import hospital.model.user.UserInfo;
import hospital.order.mapper.OrderMapper;
import hospital.order.service.OrderService;

import hospital.order.service.RefoundInfoService;
import hospital.order.service.WeiXinService;
import hospital.rabbitmq.constant.MqConst;
import hospital.rabbitmq.service.RabbitService;
import hospital.result.ResultCodeEnum;
import hospital.userClient.UserFeignClient;
import hospital.vo.hosp.ScheduleOrderVo;
import hospital.vo.msm.MsmVo;
import hospital.vo.order.*;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author
 * @description:
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper,OrderInfo> implements OrderService {
    @Autowired
    private HospFeignClient hospFeignClient;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private RefoundInfoService refoundInfoService;
    @Autowired
    private WeiXinService weiXinService;
    /**
     * @Author yang
     * @Description //TODO 生成挂号订单
     * @Param [scheduleId, patientId]
     * @return 
     **/
    @Override
    public Long saveOrder(String scheduleId, Long patientId) {
        //获取订单信息
        ScheduleOrderVo scheduleOrderVo = hospFeignClient.getScheduleOrderVo(scheduleId);

        //获取医院 签名信息
        SignInfoVo signInfo = hospFeignClient.getSignInfoVo(scheduleOrderVo.getHoscode());

        //获取就诊人信息
        Patient patient = userFeignClient.getPatientOrder(patientId);


        //判断当前时间是否还可以预约
        if(new DateTime(scheduleOrderVo.getStartTime()).isAfterNow()
                || new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()) {
            throw new HospitalException(ResultCodeEnum.TIME_NO);
        }


        //将现有的数据封装到orderInfo类中
        OrderInfo orderInfo=new OrderInfo();
        this.paketOrderInfo(orderInfo,scheduleOrderVo,patient);

        //添加到数据库中
        baseMapper.insert(orderInfo);

        //调用医院接口，实现预约挂号操作
        //设置调用医院接口需要参数，参数放到map集合
        Map<String, Object> paramMap = new HashMap<>();
        //封装调用医院接口需要参数，参数放到map集合
        //System.out.println(signInfo.getSignKey()+"utils.MD5.encrypt(MD5.java:13)");
        this.paketParamMap(paramMap,orderInfo,patient,signInfo);

        //请求医院系统接口 返回来数的数据就是可预约数量变少等封装在内的对象，我们取出字段更新到我们数据库的排班表就可以了
        //用这个报错。我们用下面的 JSONObject result = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl() + "/order/submitOrder");
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, signInfo.getApiUrl() + "/order/submitOrder");

        if(result.getInteger("code")==200) {
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");;
            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");;
            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");;
            //更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            baseMapper.updateById(orderInfo);


            //排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");


            //发送mq消息，号源更新和短信通知
            //发送mq信息更新号源
            OrderMqVo orderMqVo = new OrderMqVo();
            //使用的 排班编号（医院自己的排班主键） 是个整数，没有包含英文字母
            orderMqVo.setScheduleId(scheduleOrderVo.getHosScheduleId());
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午" : "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("amount", orderInfo.getAmount());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
                put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
            }};
            msmVo.setParam(param);
            orderMqVo.setMsmVo(msmVo);
            //发送信息到消息队列！  即生产者！ 生产订单消息到订单消息队列
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);

        } else {
            throw new HospitalException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
        return orderInfo.getId();
    }

    /**
     * @Author yang
     * @Description //TODO 获取订单详情
     * @Param [orderId]
     * @return
     **/
    @Override
    public OrderInfo getOrderInfo(String orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        return this.paketOrderInfoStatus(orderInfo);
    }
    //封装订单的状态
    private OrderInfo paketOrderInfoStatus(OrderInfo orderInfo){
        Map<String, Object> param = orderInfo.getParam();
        //设置订单的状态
        param.put("orderStatusString",OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }

    /**
     * @Author yang
     * @Description //TODO 获取订单列表
     * @Param [page, limit, userId, orderQueryVo]
     * @return
     **/
    @Override
    public Page<OrderInfo> getPageList(Integer page, Integer limit, Long userId, OrderQueryVo orderQueryVo) {
        //设置分页条件
        Page<OrderInfo> pageParams=new Page<>(page,limit);
        //获取查询条件
        //医院名称
        String name = orderQueryVo.getKeyword();
        //订单状态状态
        String orderStatus = orderQueryVo.getOrderStatus();
        //就诊人ID
        Long patientId = orderQueryVo.getPatientId();
        //安排时间
        String reserveDate = orderQueryVo.getReserveDate();
        //开始时间
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        //结束时间
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();
        //封装查询条件
        QueryWrapper<OrderInfo> wrapper=new QueryWrapper<>();
        if(!StringUtils.isNullOrEmpty(name)){
            wrapper.like("hosname",name);
        }
        if(null!=orderStatus){
            wrapper.eq("order_status",orderStatus);
        }
        if(null!=patientId){
            wrapper.eq("patient_id",patientId);
        }
        if(!StringUtils.isNullOrEmpty(reserveDate)){
            wrapper.ge("reserve_date",reserveDate);
        }
        if(!StringUtils.isNullOrEmpty(createTimeBegin)){
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isNullOrEmpty(createTimeEnd)){
            wrapper.le("create_time",createTimeEnd);
        }

        Page<OrderInfo> infoPage = baseMapper.selectPage(pageParams, wrapper);

        //封装用户状态和认证状态
        infoPage.getRecords().stream().forEach( item ->{
            this.paketOrderInfoStatus(item);
        });
        return infoPage;
    }

    /**
     * @Author yang
     * @Description //TODO 取消预约
     * @Param [orderId]
     * @return
     **/
    @Override
    public Boolean cancelOrder(Long orderId) {
        //1.获取订单信息
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        //2. 判断是否超过退号时间
//        if(new DateTime(orderInfo.getQuitTime()).isBeforeNow()){
//            throw new HospitalException(ResultCodeEnum.CANCEL_ORDER_NO);
//        }

        //3. //调用医院接口实现预约取消
        SignInfoVo signInfoVo = hospFeignClient.getSignInfoVo(orderInfo.getHoscode());
        if(null==signInfoVo){
            throw new HospitalException(ResultCodeEnum.DATA_ERROR);
        }

        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode",orderInfo.getHoscode());
        reqMap.put("hosRecordId",orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
        reqMap.put("sign", sign);

     /*   JSONObject result = HttpRequestHelper.sendRequest(reqMap,
                signInfoVo.getApiUrl()+"/order/updateCancelStatus");*/

        System.err.println(signInfoVo.getApiUrl()+"/order/updateCancelStatus");

        JSONObject result = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl()+"/order/updateCancelStatus");
        //根据医院接口返回数据
        if(result.getInteger("code")!=200) {
            throw new HospitalException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        } else {
            //判断当前订单是否可以取消  可以的话调用微信退款方法
            if(orderInfo.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus().intValue()) {
                Boolean isRefund = weiXinService.refund(orderId);
                if(!isRefund) {
                    throw new HospitalException(ResultCodeEnum.CANCEL_ORDER_FAIL);
                }
                //更新订单状态
                orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
                baseMapper.updateById(orderInfo);

                //发送mq更新预约数量
                OrderMqVo orderMqVo = new OrderMqVo();
                orderMqVo.setScheduleId(orderInfo.getScheduleId());

                //短信提示
                MsmVo msmVo = new MsmVo();
                msmVo.setPhone(orderInfo.getPatientPhone());
                String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
                Map<String,Object> param = new HashMap<String,Object>(){{
                    put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                    put("reserveDate", reserveDate);
                    put("name", orderInfo.getPatientName());
                }};
                msmVo.setParam(param);
                orderMqVo.setMsmVo(msmVo);
                rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
            }
        }
        return true;
    }

    /**
     * @Author yang
     * @Description //TODO 监听定时任务的消息 即我是定时任务消费者
     * @Param []
     * @return
     **/
    @Override
    public void patientTips() {
        //根据当前时间 8点，和支付状态查询出，需要提醒的列表
        QueryWrapper<OrderInfo> wrapper=new QueryWrapper<>();
        wrapper.eq("reserve_date",new DateTime(new Date()).toString("yyyy-MM-dd"));
        //不是取消预约的
        wrapper.ne("order_status",OrderStatusEnum.CANCLE);
        //使用mq短信提醒
        List<OrderInfo> orderInfoList = baseMapper.selectList(wrapper);
        for(OrderInfo orderInfo:orderInfoList) {
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
                put("jiuyitixing","就医提醒"); //为了能够走不同的短信模板多设置一个值来给后面的方法区分
            }};
            msmVo.setParam(param);
            //短信提醒是借助前面我们写的短信mq，这里是短信生产者
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        }
    }

    /**
     * @Author yang
     * @Description //TODO //统计预约挂号的数量
     * @Param [orderCountQueryVo]
     * @return 
     **/
    @Override
    public Map<String, Object> getCountMap(OrderCountQueryVo orderCountQueryVo) {
        //查询出预约的值
        List<OrderCountVo> countMap = baseMapper.getCountMap(orderCountQueryVo);

        //设置 x轴的日期 list集合
        List<String> dateList = countMap.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());

        //设置 y轴的预约数 list集合
        List<Integer> countList = countMap.stream().map(OrderCountVo::getCount).collect(Collectors.toList());

        Map<String, Object> map=new HashMap<>();
        map.put("dateList",dateList);
        map.put("countList",countList);
        return map;
    }

    /**
     * @Author yang
     * @Description //TODO //封装调用医院接口需要参数，参数放到map集合
     * @Param [paramMap, orderInfo, patient, signInfo]
     * @return
     **/
    private void paketParamMap(Map<String, Object> paramMap,OrderInfo orderInfo, Patient patient,SignInfoVo signInfo){
        paramMap.put("hoscode",orderInfo.getHoscode());
        paramMap.put("depcode",orderInfo.getDepcode());
        paramMap.put("hosScheduleId",orderInfo.getScheduleId());
        paramMap.put("reserveDate",new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount",orderInfo.getAmount());

        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType",patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex",patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone",patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode",patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode",patient.getDistrictCode());
        paramMap.put("address",patient.getAddress());
        //联系人
        paramMap.put("contactsName",patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone",patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());

        String sign = HttpRequestHelper.getSign(paramMap, signInfo.getSignKey());
        paramMap.put("sign", sign);
    }
    /**
     * @Author yang
     * @Description //TODO 将现有的数据封装到orderInfo类中
     * @Param
     * @return
     **/
    private void paketOrderInfo(OrderInfo orderInfo, ScheduleOrderVo scheduleOrderVo, Patient patient) {
        //scheduleOrderVo 复制到orderInfo
        BeanUtils.copyProperties(scheduleOrderVo,orderInfo);

        //封装其他数据
        String outTradeNo = System.currentTimeMillis() + ""+ new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTradeNo);
        orderInfo.setScheduleId(scheduleOrderVo.getHosScheduleId());
        orderInfo.setUserId(patient.getUserId());
        orderInfo.setPatientId(patient.getUserId());
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
    }
}
